package guis;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuDetectEvent;
import org.eclipse.swt.events.MenuDetectListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolTip;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;

public class TrayIcon {

    private Display ownerDisplay;
    private Shell ownerShell;
    private Tray tray;
    private TrayItem trayIcon;
    private Menu tray_menu;

    // private List<MenuItem> menu_items;

    // will removed
    private MenuItem menu_exit_item;
    private MenuItem open_window_item;
    private MenuItem menu_state_item;
    private MenuItem order_state_item;

    //

    public TrayIcon(Display display, Shell shell) {

	ownerDisplay = display;
	ownerShell = shell;

	Image image = null;// will added later
	image = display.getSystemImage(SWT.ICON_INFORMATION);

	tray = display.getSystemTray();
	trayIcon = new TrayItem(tray, SWT.NONE);
	trayIcon.setImage(image);

	tray_menu = new Menu(ownerShell, SWT.POP_UP);

	open_window_item = new MenuItem(tray_menu, SWT.PUSH);
	open_window_item.setText("Open");
	open_window_item.addListener(SWT.Selection, new Listener() {
	    @Override
	    public void handleEvent(Event e) {
		ownerShell.open();
	    }
	});

	menu_state_item = new MenuItem(tray_menu, SWT.PUSH);
	menu_state_item.setText("Update Menu");
	menu_state_item.setEnabled(false);

	order_state_item = new MenuItem(tray_menu, SWT.PUSH);
	order_state_item.setText("Make Order");
	order_state_item.setEnabled(false);

	menu_exit_item = new MenuItem(tray_menu, SWT.PUSH);
	menu_exit_item.setText("Exit");
	menu_exit_item.addListener(SWT.Selection, new Listener() {
	    @Override
	    public void handleEvent(Event e) {
		ownerShell.close();
	    }
	});

	trayIcon.addMenuDetectListener(new MenuDetectListener() {
	    @Override
	    public void menuDetected(MenuDetectEvent e) {
		tray_menu.setVisible(true);
	    }
	});

	trayIcon.addSelectionListener(new SelectionAdapter() {
	    @Override
	    public void widgetSelected(SelectionEvent e) {
		Icon_Left_Click();
	    }
	});
    }

    public void Show_Noinify(String text) {

	final ToolTip tip = new ToolTip(ownerShell, SWT.ICON_INFORMATION
		| SWT.BALLOON);
	tip.setMessage(text);

	trayIcon.setImage(ownerDisplay.getSystemImage(SWT.ICON_QUESTION));
	tip.setText("Lunchy");
	trayIcon.setToolTip(tip);
	tip.setVisible(true);
	tip.setAutoHide(false);
    }

    private void Icon_Left_Click() {
	// open main window
	ownerShell.open();
    }

}
